package dao

import (
	"GoMaestro/internal/conf"
	"GoMaestro/internal/entity"
	"GoMaestro/internal/entity/app"
)

// MysqlDao 这里直接定义方法不写接口，目前只需要使用mysql数据库(懒得写接口了)
type MysqlDao struct{}

func (j *MysqlDao) SelectAppByID(appID int) (app.App, error) {
	var App app.App
	err := conf.MysqlDataConnect.Where("app_id = ?", appID).First(&App).Error
	return App, err
}

func (j *MysqlDao) SelectAppConfigByAppIdAndEnv(appId int, env string) (entity.AppConfig, error) {
	var appConfig entity.AppConfig
	err := conf.MysqlDataConnect.Where("app_id = ? AND env = ?", appId, env).First(&appConfig).Error
	return appConfig, err
}

func (j *MysqlDao) SelectEnvConfigByEnvName(env string) (entity.EnvConfig, error) {
	var envConfig entity.EnvConfig
	err := conf.MysqlDataConnect.Where("env = ?", env).First(&envConfig).Error
	return envConfig, err
}

func (j *MysqlDao) SelectPipelinesByCodePackageType(codePackageType string) (entity.Pipeline, error) {
	var pipelines entity.Pipeline
	err := conf.MysqlDataConnect.Where("code_package_type = ?", codePackageType).First(&pipelines).Error
	return pipelines, err
}

func (j *MysqlDao) InsertTask(task *entity.TaskRecord) error {
	return conf.MysqlDataConnect.Create(&task).Error
}

func (j *MysqlDao) SelectTaskStatus() ([]entity.TaskRecord, error) {
	var taskRecords []entity.TaskRecord
	err := conf.MysqlDataConnect.
		Where("status = ?", entity.StatusPackaging).
		Or("status = ?", entity.StatusPackaged).
		Or("status = ?", entity.StatusDeploying).
		Find(&taskRecords).
		Error

	if err != nil {
		return nil, err
	}
	return taskRecords, err
}

func (j *MysqlDao) UpdateTask(task *entity.TaskRecord) error {
	return conf.MysqlDataConnect.Updates(&task).Error
}
